import xml.etree.ElementTree as ET
import os


def parse_failed_cases():
    """Parse JUnit XML report and extract failed test cases"""
    try:
        tree = ET.parse('junit-results.xml')
        root = tree.getroot()

        failed_cases = []
        for testcase in root.findall('.//testcase'):
            if testcase.find('failure') is not None or testcase.find('error') is not None:
                classname = testcase.get('classname', 'UnknownClass')
                testname = testcase.get('name', 'UnknownTest')
                short_classname = classname.split('.')[-1]
                failed_cases.append(f'{short_classname}.{testname}')

        if failed_cases:
            failed_count = len(failed_cases)
            display_cases = failed_cases[:5]
            failed_text = '\n'.join([f'• {case}' for case in display_cases])

            if failed_count > 5:
                failed_text += f'\n• ... and {failed_count - 5} more failed cases'

            print(f'Found {failed_count} failed test cases')
        else:
            failed_text = '• No failed test cases'
            print('No failed test cases found')

        with open('failed_cases.txt', 'w', encoding='utf-8') as f:
            f.write(failed_text)

        return True

    except Exception as e:
        print(f'Error parsing XML report: {e}')
        with open('failed_cases.txt', 'w', encoding='utf-8') as f:
            f.write('• Failed to parse test report')
        return False


if __name__ == "__main__":
    parse_failed_cases()